/**
 * name: common
 * version: v4.1.2
 * update: placeholder inline
 * date: 2017-05-11
 */
define(function (require, exports, module) {
    var $ = require('jquery');
    var base = require('base');
    if (base.browser.ie < 8) {
        alert('您的浏览器版本过低，请升级或使用chrome、Firefox等高级浏览器！');
        //屏蔽ie78 console未定义错误
        if (typeof console === 'undefined') {
            console = {
                log: function () {
                },
                warn: function () {
                }
            };
        }
    }
    //返回顶部
    $('body').on('click', '.gotop', function () {
        $('html,body').stop(1).animate({
            scrollTop: '0'
        }, 300);
        return false;
    });
    //textarea扩展max-length
    $('textarea[max-length]').on('change blur keyup', function () {
        var _val = $(this).val(),
            _max = $(this).attr('max-length');
        if (_val.length > _max) {
            $(this).val(_val.substr(0, _max));
        }
    });

    //延时显示
    if (base.browser.ie < 9) {
        $('.opc0').css('filter', 'unset');
    } else {
        $('.opc0').animate({
            'opacity': '1'
        }, 160);
    }

    // placeholder
    (function () {
        var isOperaMini = Object.prototype.toString.call(window.operamini) == '[object OperaMini]';
        var isInputSupported = 'placeholder' in document.createElement('input') && !isOperaMini;
        var isTextareaSupported = 'placeholder' in document.createElement('textarea') && !isOperaMini;
        var valHooks = $.valHooks;
        var propHooks = $.propHooks;
        var hooks;
        var placeholder;
        if (isInputSupported && isTextareaSupported) {
            placeholder = $.fn.placeholder = function () {
                return this
            };
            placeholder.input = placeholder.textarea = true
        } else {
            var settings = {};
            placeholder = $.fn.placeholder = function (options) {
                var defaults = {
                    customClass: 'placeholder'
                };
                settings = $.extend({}, defaults, options);
                var $this = this;
                $this.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]').not('.' + settings.customClass).bind({
                    'focus.placeholder': clearPlaceholder,
                    'blur.placeholder': setPlaceholder
                }).data('placeholder-enabled', true).trigger('blur.placeholder');
                return $this
            };
            placeholder.input = isInputSupported;
            placeholder.textarea = isTextareaSupported;
            hooks = {
                'get': function (element) {
                    var $element = $(element);
                    var $passwordInput = $element.data('placeholder-password');
                    if ($passwordInput) {
                        return $passwordInput[0].value
                    }
                    return $element.data('placeholder-enabled') && $element.hasClass(settings.customClass) ? '' : element.value
                },
                'set': function (element, value) {
                    var $element = $(element);
                    var $passwordInput = $element.data('placeholder-password');
                    if ($passwordInput) {
                        return $passwordInput[0].value = value
                    }
                    if (!$element.data('placeholder-enabled')) {
                        return element.value = value
                    }
                    if (value === '') {
                        element.value = value;
                        if (element != safeActiveElement()) {
                            setPlaceholder.call(element)
                        }
                    } else if ($element.hasClass(settings.customClass)) {
                        clearPlaceholder.call(element, true, value) || (element.value = value)
                    } else {
                        element.value = value
                    }
                    return $element
                }
            };
            if (!isInputSupported) {
                valHooks.input = hooks;
                propHooks.value = hooks
            }
            if (!isTextareaSupported) {
                valHooks.textarea = hooks;
                propHooks.value = hooks
            }
            $(function () {
                $(document).delegate('form', 'submit.placeholder', function () {
                    var $inputs = $('.' + settings.customClass, this).each(clearPlaceholder);
                    setTimeout(function () {
                        $inputs.each(setPlaceholder)
                    }, 10)
                })
            });
            $(window).bind('beforeunload.placeholder', function () {
                $('.' + settings.customClass).each(function () {
                    this.value = ''
                })
            })
        }

        function args(elem) {
            var newAttrs = {};
            var rinlinejQuery = /^jQuery\d+$/;
            $.each(elem.attributes, function (i, attr) {
                if (attr.specified && !rinlinejQuery.test(attr.name)) {
                    newAttrs[attr.name] = attr.value
                }
            });
            return newAttrs
        }

        function clearPlaceholder(event, value) {
            var input = this;
            var $input = $(input);
            if (input.value == $input.attr('placeholder') && $input.hasClass(settings.customClass)) {
                if ($input.data('placeholder-password')) {
                    $input = $input.hide().nextAll('input[type="password"]:first').show().attr('id', $input.removeAttr('id').data('placeholder-id'));
                    if (event === true) {
                        return $input[0].value = value
                    }
                    $input.focus()
                } else {
                    input.value = '';
                    $input.removeClass(settings.customClass);
                    input == safeActiveElement() && input.select()
                }
            }
        }

        function setPlaceholder() {
            var $replacement;
            var input = this;
            var $input = $(input);
            var id = this.id;
            if (input.value === '') {
                if (input.type === 'password') {
                    if (!$input.data('placeholder-textinput')) {
                        try {
                            $replacement = $input.clone().attr({
                                'type': 'text'
                            })
                        } catch (e) {
                            $replacement = $('<input>').attr($.extend(args(this), {
                                'type': 'text'
                            }))
                        }
                        $replacement.removeAttr('name').data({
                            'placeholder-password': $input,
                            'placeholder-id': id
                        }).bind('focus.placeholder', clearPlaceholder);
                        $input.data({
                            'placeholder-textinput': $replacement,
                            'placeholder-id': id
                        }).before($replacement)
                    }
                    $input = $input.removeAttr('id').hide().prevAll('input[type="text"]:first').attr('id', id).show()
                }
                $input.addClass(settings.customClass);
                $input[0].value = $input.attr('placeholder')
            } else {
                $input.removeClass(settings.customClass)
            }
        }

        function safeActiveElement() {
            try {
                return document.activeElement
            } catch (exception) {
            }
        }
    })();
    $('input, textarea').placeholder();


    /*
     * 输出
     */
    module.exports = {
        demo: function () {
            var directHash = {
                "0": "重定向",
                "1": "刷新",
                "2": "历史记录"
            };
            console.log('页面来自' + directHash[window.performance.navigation.type]);
        },
        initEditor: function (id) {

        }
    };

    /*
     * 站内公用
     */

    var resp = require('responsive');
    //无回调
    var deviceType = resp.getType();      //"Pc" || "Pad" || "Mobile"
    console.log(deviceType, '当前设备');
    if (deviceType != 'Pc') {
        require('offcanvas');
        $('.pageNav').offcanvas({
            classes: 'mm-white'
        });
    }

    if (deviceType != 'Mobile') {
        var footH = $('.pageFooter').outerHeight();
        $('body').css('padding-bottom', footH);
    }


    //头部搜索下拉筛选
    $('.headSearch').on('click', '.option', function () {
        var $text = $(this).html(),
            $val = $(this).data('val'),
            $seleted = $(this).parents('.select').find('.selected'),
            $seleted_input = $seleted.next('input[name="selected"]');
        $seleted.html($text);
        $seleted_input.val($val);
    });


    var Box = require('box');
    //登录弹窗
    $('.goLogin').on('click', function () {
        Box.open($('.loginForm'), {
            title: '欢迎登录'
        });
    });
    //注册弹窗
    $('.goRegist').on('click', function () {
        Box.hide();
        setTimeout(function () {
            Box.open($('.registForm'), {
                title: '账号注册',
                onshow: function (box) {
                    //console.log(box,'box');
                    initCode();
                }
            });
        }, 200);
    });

    require('validform');
    //登录表单
    var loginForm = $('#login_form').Validform({
        ajaxPost: true,
        ajaxData: function () {
            return {_csrf: $('meta[name="csrf-token"]').attr("content")};
        },
        url: $(this).attr('action'),
        callback: function (res) {
            // 登录成功回调
            if (res.error == 0) {
                document.location.reload();
            } else {
                Box.toast(res.msg);
            }
        }
    });

    //注册表单
    var registForm = $('#reg_form').Validform({
        ajaxPost: true,
        url: $(this).attr('action'),
        ajaxData: function () {
            return {_csrf: $('meta[name="csrf-token"]').attr("content")};
        },
        callback: function (res) {
            // 注册成功回调
            Box.hide(); //关闭所有弹窗
            if (res.error == 0) {
                setTimeout(function () {
                    //注册成功提示
                    Box.alert('恭喜您注册成功', function () {
                        //点击关闭后回调
                        document.location.reload();
                    }, {
                        hook: 'box_success',
                        title: '',
                        oktext: '关闭'
                    });
                }, 200)
            } else {
                Box.toast(res.msg);
            }
        }
    });

    //发送验证码
    require('sendcode');
    function initCode(num) {
        var url = $('#codeBtn').data('url');
        $('#codeBtn').sendcode({
            mobile: num,
            time: 120,
            keyName: 'mobile',
            render: function (sec) {
                return sec + 's';
            },
            url: url,
            sendBefore: function (mobile) {
                //请求前
                return true;
            },
            sendAfter: function (res) {
                //请求成功后
                console.log(1111);
                console.log(res);
            },
            error: function (error) {
                //error
                Box.toast('请输入手机号！');
            }
        });
    }

    //注册手机号每次blur后，给发送验证码插件传递手机号码
    $('body').on('blur', '.reg_mobile', function () {
        var mobileNum = $(this).val();
        initCode(mobileNum)
    })


});